<style lang="less">
    @import '../../../styles/common.less';
</style>

<template>
    <div>
        <Row :gutter="10">
            <Col span="6">
            <Card>
                <p slot="title">
                    <Icon type="ios-toggle"></Icon>
                        资源列表
                </p>
                <Tree ref="resources" :data="resources" @on-select-change="onSelectChange"></Tree>
            </Card>
            </Col>
            <Col span="18">
            <Card>
                <p slot="title">
                    <Icon type="ios-cog"></Icon>
                    资源明细
                </p>
                <Row :gutter="10" type="flex" justify="center" align="middle" class="switch-language-row1">
                    <Col span="24" >
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                        <FormItem label="资源名称" prop="name">
                            <Input v-model="formValidate.name" placeholder="输入资源名称"></Input>
                        </FormItem>
                        <FormItem label="资源URL" prop="url">
                            <Input v-model="formValidate.url" placeholder="输入资源url"></Input>
                        </FormItem>
                        <FormItem label="资源编码" prop="code">
                            <Input v-model="formValidate.code" placeholder="输入资源编码"></Input>
                        </FormItem>
                        <FormItem label="父菜单" prop="parentId">
                            <Cascader :data="records" filterable v-model="formValidate.fullParentIds" trigger="click" change-on-select></Cascader>
                        </FormItem>
                        <FormItem label="资源类型" prop="type">
                            <Select  v-model="formValidate.type" placeholder="选择资源类型">
                                <i-option  v-for="resourceType in resourceTypeEnums" :value="resourceType.code" :key="resourceType.code">{{resourceType.name}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="资源标识" prop="permission" >
                            <Tooltip placement="top" max-width="200" content="选择*该资源编码下所有资源将被授权">
                            <Select  v-model="formValidate.permission" placeholder="选择资源标识" style="width: 150px;">
                                <Option value="*">*</Option>
                                <Option value="create">create</Option>
                                <Option value="update">update</Option>
                                <Option value="delete">delete</Option>
                                <Option value="read">read</Option>
                            </Select>
                            </Tooltip>
                        </FormItem>
                        <FormItem label="资源图标" prop="icon" v-if="formValidate.type == 'MENU'">
                            <Input v-model="formValidate.icon" placeholder="输入资源图标"></Input>
                        </FormItem>
                        <FormItem label="前端组件" prop="component" v-if="formValidate.type == 'MENU'">
                            <Input v-model="formValidate.component" placeholder="输入前端组件"></Input>
                        </FormItem>
                        <FormItem label="显示顺序" prop="priority" v-if="formValidate.type == 'MENU'">
                            <Select v-model="formValidate.priority" placeholder="选择显示顺序" :disabled="formValidate.type != 'MENU'">
                                <i-option  v-for="sort in 10" :value="sort" :key="sort">{{sort}}</i-option>
                            </Select>
                        </FormItem>

                        <FormItem label="元数据" prop="meta" v-if="formValidate.type == 'MENU'">
                            <Input v-model="formValidate.meta" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入资源元数据(json格式)"></Input>
                        </FormItem>
                       <FormItem label="状态" prop="status">
                            <i-switch v-model="statusBoolean" size="large">
                                <span slot="NORMAL">有效</span>
                                <span slot="INVALID">失效</span>
                            </i-switch>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" @click="handlePostOrPut('formValidate')">保存</Button>
                            <Button  @click="handleRest()" style="margin-left: 8px">重置</Button>
                        </FormItem>
                    </Form>
                    </Col>
                </Row>
            </Card>
            </Col>
        </Row>
    </div>
</template>

<script type="text/ecmascript-6">
    import api  from '../../../libs/api'
    import util from '../../../libs/util'
    import filters from '../../../libs/filters'
    import validator from "../../../libs/validator"
    export default {
        name: 'resource',
        data () {
            //自定义验证
            var validateCode = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error('请输入资源编码'));
                } else {
                    if (this.formValidate.url !== ""&&this.formValidate.url.indexOf(value)<0) {
                        callback(new Error("资源编码需与资源路径前缀保持一致"));
                    }
                    callback();
                }
            };
            var validatePermission=(rule, value, callback) => {
                if (value === "") {
                    callback(new Error('请选择资源标识'));
                } else {
                    if (this.formValidate.fullParentIds == ""&&this.formValidate.type!=""&&this.formValidate.type!="BUTTON"&&value!="*") {
                        callback(new Error("父级别资源标识请选择*"));
                    }else if(value=="*"&&this.formValidate.fullParentIds!=""&&this.formValidate.type=="BUTTON"){
                        callback(new Error("子级别资源标识不允许*标识"));
                    }
                    callback();
                }
            };
            return {
                resources:[
                    {
                        title: '资源列表',
                        expand: true,
                        children: []
                    }
                ],
                records:[],
                resourceTypeEnums:[], //菜单类型
                statusBoolean:true,
                formValidate: {
                    id:"",
                    name: '',
                    url: '',
                    code: '',
                    type:"",
                    icon:"",
                    priority:"",
                    parentId:"",
                    status:"NORMAL",
                    meta: '',
                    fullParentIds:[],
                    permission:""
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '资源名称不允许为空额', trigger: 'blur' }
                    ],
                    url: [
                        { required: true, message: '资源URL不允许为空', trigger: 'blur' }
                    ],
                    code:[
                        { required: true, message: '资源编码不允许为空', trigger: 'blur' },
                        { validator: validateCode, trigger: 'blur' }
                    ],
                    permission:[
                        { required: true, message: '资源标识不允许为空', trigger: 'blur' },
                        { validator: validatePermission, trigger: 'change' }
                    ],
                    type:[
                        { required: true, message: '资源类型不允许为空', trigger: 'blur' }
                    ],
                    meta:[ { validator:validator.json, trigger: 'change' }]
                }
            }
        },
        methods: {
            onSelectChange(data){
                data.expand=!data.expand;
                if(typeof data[0] != "undefined"){
                    this.formValidate=JSON.parse(JSON.stringify(data[0]));  //深度拷贝数据
                    this.resourceTypeEnums=this.formValidate.resourceTypeEnums;
                }
            },
            //重置
            handleRest(){
                this.$refs["formValidate"].resetFields();
                this.formValidate.fullParentIds=[];
                this.formValidate.id="";
            },
            //读取数据
            handleRead(){
                let self=this;
                let data = {};
                this.$get(api.resources.tree, data).then(response => {
                    var records=[];
                    response.obj.forEach(function (resource) {
                        resource.permission=resource.permission.split(":")[1];
                        //树形tree所需数据格式
                        resource.title=resource.name;
                        resource.expand=false;
                        //级联组件所需数据格式
                        resource.value=resource.id;
                        resource.label=resource.name;
                        resource.fullParentIds=filters.split(resource.fullParentIds,"/",[]);
                        self.handleTree(resource);
                        records.push(resource);
                    });
                    self.resources.children=records;
                    self.records=records;
                    self.resourceTypeEnums=records.length>0?records[0].resourceTypeEnums:[];
                    self.$set(self.resources[0], 'children', this.records);
                });
            },
            handleTree(resource){
                var self=this;
                var childrenArray=[];
                resource.childrensView&&resource.childrensView.forEach(function (childrens) {
                    childrens.permission=childrens.permission.split(":")[1];
                    var children={};
                    children=childrens;
                    //树形tree所需数据格式
                    children.title=childrens.name;
                    children.expand=false;
                    //级联组件所需数据格式
                    children.value=childrens.id;
                    children.label=childrens.name;

                    children.fullParentIds=filters.split(children.fullParentIds,"/",[]);
                    childrenArray.push(children);
                });
                resource.children=childrenArray;
                childrenArray.forEach(function (item) {
                    if(item.childrensView&&item.childrensView.length>0)
                        self.handleTree(item);
                    else
                        item.children=[];
                })
            },
            handlePostOrPut (name) {
                let self=this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        //去除冗余请求数据
                        delete self.formValidate["children"];
                        delete self.formValidate["childrensView"];
                        let formValidate=util.deepCopy(self.formValidate);
                        formValidate.permission= formValidate.code+":"+ formValidate.permission;
                        formValidate.parentId=formValidate.fullParentIds.length>0?formValidate.fullParentIds[formValidate.fullParentIds.length-1]:"";
                        formValidate.fullParentIds=formValidate.fullParentIds.length>0?filters.separatorArray(formValidate.fullParentIds,"/"):"";
                        if(self.formValidate.id==""){   //新增
                            self.$post(api.resources.base,formValidate).then(response => {
                                if(200==response.code){
                                    self.handleRest();
                                    self.handleRead();
                                }
                            });
                        }else{  //更新
                            self.$put(api.resources.base+"/"+self.formValidate.id,formValidate).then(response=>{
                               if(200==response.code){
                                   self.handleRest();
                                   self.handleRead();
                               }
                            });
                        }
                    }
                })
            },
        },
        created(){
            this.handleRead();
        },
        watch:{
            statusBoolean:function(val, oldVal) {
                this.formValidate.status=val?"NORMAL":"INVALID";
            }
        }
    }
</script>

<style>

</style>
